<template>
  <div class="container">
    <div class="filter-container">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="医生姓名">
          <el-input v-model="searchForm.doctorName" placeholder="请输入医生姓名" />
        </el-form-item>
        <el-form-item label="科室">
          <el-cascader
            v-model="searchForm.deptId"
            :options="departmentOptions"
            :props="{ 
              checkStrictly: true,
              value: 'id',
              label: 'departmentName',
              children: 'children'
            }"
            placeholder="请选择科室"
            clearable
          />
        </el-form-item>
        <el-form-item label="职称">
          <el-select v-model="searchForm.jobTitleId" placeholder="请选择职称" style="width: 100%">
            <el-option v-for="item in titleOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select v-model="searchForm.status" placeholder="请选择审核状态">
            <el-option label="全部" value="" />
            <el-option label="未审核" value="未审核" />
            <el-option label="已通过" value="已通过" />
            <el-option label="未通过" value="未通过" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">筛选</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="审核通过" name="approved"></el-tab-pane>
      <el-tab-pane label="审核未通过" name="rejected"></el-tab-pane>
    </el-tabs>

    <div class="table-container">
      <div class="table-header">
        <el-button type="danger" :disabled="selectedDoctors.length === 0" @click="handleBatchDelete">批量删除</el-button>
      </div>
      
      <el-table 
        :data="doctorList" 
        border 
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="doctorName" label="姓名" width="120" />
        <el-table-column prop="mobile" label="电话" width="150" />
        <el-table-column prop="hospitalName" label="医院" />
        <el-table-column prop="departmentName" label="科室" width="120" />
        <el-table-column prop="jobTitleName" label="职称" width="120" />
        <el-table-column prop="status" label="审核状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" align="center">
          <template #default="scope">
            <el-button size="small" @click="viewDoctor(scope.row)">查看</el-button>
            <el-button v-if="scope.row.status !== '已通过'" size="small" type="success" @click="approveDoctor(scope.row)">通过</el-button>
            <el-button v-if="scope.row.status !== '未通过'" size="small" type="danger" @click="rejectDoctor(scope.row)">拒绝</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="searchForm.pageSize"
          :current-page="searchForm.pageIndex"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 审核详情对话框 -->
    <el-dialog v-model="auditDialogVisible" title="医生资质审核" width="70%">
      <div class="audit-content">
        <div class="doctor-info">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="姓名">{{ currentDoctor.doctorName }}</el-descriptions-item>
            <el-descriptions-item label="电话">{{ currentDoctor.mobile }}</el-descriptions-item>
            <el-descriptions-item label="医院">{{ currentDoctor.hospitalName }}</el-descriptions-item>
            <el-descriptions-item label="科室">{{ currentDoctor.departmentName }}</el-descriptions-item>
            <el-descriptions-item label="职称">{{ currentDoctor.jobTitleName }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="doctor-certificates">
          <h3>资质证书</h3>
          <div class="cert-images">
            <div class="cert-item">
              <p>执业证书</p>
              <el-image :src="currentDoctor.occupationCertificate || 'https://via.placeholder.com/300x200?text=无执业证书'" fit="contain" :preview-src-list="[currentDoctor.occupationCertificate]"></el-image>
            </div>
            <div class="cert-item">
              <p>职称证书</p>
              <el-image :src="currentDoctor.rankCertificate || 'https://via.placeholder.com/300x200?text=无职称证书'" fit="contain" :preview-src-list="[currentDoctor.rankCertificate]"></el-image>
            </div>
          </div>
        </div>

        <div class="audit-form">
          <el-form :model="auditForm">
            <el-form-item label="审核意见">
              <el-input v-model="auditForm.comment" type="textarea" :rows="4" placeholder="请输入审核意见"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmReject">拒绝</el-button>
          <el-button type="primary" @click="confirmApprove">通过</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDoctors, getDepartmentsCascade } from '@/http/axiosRead'
import { deleteDoctor, batchDeleteDoctors } from '@/http/axiosWrtie'

interface Doctor {
  id: number;
  doctorName: string;
  mobile: string;
  hospitalName: string;
  departmentName: string;
  jobTitleName: string;
  status: string;
  occupationCertificate: string;
  rankCertificate: string;
  [key: string]: any;
}

const searchForm = reactive({
  doctorName: '',
  deptId: undefined,
  jobTitleId: undefined,
  status: '',
  pageIndex: 1,
  pageSize: 10
})

const doctorList = ref<Doctor[]>([])
const total = ref(0)
const activeTab = ref('all')
const departmentOptions = ref([])
const selectedDoctors = ref<Doctor[]>([])
const titleOptions = ref([
  { id: 1, name: '主任医师' },
  { id: 2, name: '副主任医师' },
  { id: 3, name: '主治医师' },
  { id: 4, name: '住院医师' },
  { id: 5, name: '药剂师' },
  { id: 6, name: '护士' }
])

// 审核相关变量
const auditDialogVisible = ref(false)
const currentDoctor = ref({
  doctorName: '',
  mobile: '',
  hospitalName: '',
  departmentName: '',
  jobTitleName: '',
  status: '',
  occupationCertificate: '',
  rankCertificate: ''
})
const auditForm = reactive({
  comment: ''
})

onMounted(() => {
  fetchDepartmentList()
  fetchDoctorList()
})

const handleSelectionChange = (selection: Doctor[]) => {
  selectedDoctors.value = selection
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确认删除医生 ${row.doctorName}？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteDoctor(row.id)
      if (response.data && response.data.code === 200) {
        ElMessage.success('删除成功')
        fetchDoctorList()
      } else {
        ElMessage.error(response.data?.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除医生失败：', error)
      ElMessage.error('删除失败，请稍后重试')
    }
  }).catch(() => {
    // 取消删除，不做处理
  })
}

const handleBatchDelete = () => {
  if (selectedDoctors.value.length === 0) {
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${selectedDoctors.value.length} 名医生？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const ids = selectedDoctors.value.map(doctor => doctor.id)
      const response = await batchDeleteDoctors(ids)
      if (response.data && response.data.code === 200) {
        ElMessage.success('批量删除成功')
        fetchDoctorList()
      } else {
        ElMessage.error(response.data?.msg || '批量删除失败')
      }
    } catch (error) {
      console.error('批量删除医生失败：', error)
      ElMessage.error('批量删除失败，请稍后重试')
    }
  }).catch(() => {
    // 取消删除，不做处理
  })
}

const fetchDepartmentList = async () => {
  try {
    const response = await getDepartmentsCascade()
    if (response.data && response.data.data && response.data.data.departments) {
      departmentOptions.value = response.data.data.departments
    }
  } catch (error) {
    console.error('获取科室列表失败：', error)
    ElMessage.error('获取科室列表失败')
  }
}

const fetchDoctorList = async () => {
  // 根据选中的标签页设置状态
  switch(activeTab.value) {
    case 'approved':
      searchForm.status = '已通过'
      break
    case 'rejected':
      searchForm.status = '未通过'
      break
    default:
      // 'all' 标签，如果用户手动选择了状态，则保留
      if (searchForm.status !== '已通过' && searchForm.status !== '未通过' && searchForm.status !== '未审核') {
        searchForm.status = ''
      }
  }

  try {
    const response = await getDoctors(searchForm)
    doctorList.value = response.data.pageData || []
    total.value = response.data.totaCount || 0
  } catch (error) {
    console.error('获取医生列表失败：', error)
    ElMessage.error('获取医生列表失败')
  }
}

const handleTabClick = () => {
  searchForm.pageIndex = 1
  fetchDoctorList()
}

const onSearch = () => {
  searchForm.pageIndex = 1
  fetchDoctorList()
}

const resetForm = () => {
  searchForm.doctorName = ''
  searchForm.deptId = undefined
  searchForm.jobTitleId = undefined
  searchForm.status = ''
  activeTab.value = 'all'
  onSearch()
}

const handleSizeChange = (val: number) => {
  searchForm.pageSize = val
  fetchDoctorList()
}

const handleCurrentChange = (val: number) => {
  searchForm.pageIndex = val
  fetchDoctorList()
}

const getStatusType = (status: string) => {
  switch (status) {
    case '已通过':
      return 'success'
    case '未通过':
      return 'danger'
    case '未审核':
    default:
      return 'info'
  }
}

const getStatusText = (status: string) => {
  return status || '未审核'
}

const viewDoctor = (row: any) => {
  currentDoctor.value = row
  auditDialogVisible.value = true
  auditForm.comment = ''
}

const approveDoctor = (row: any) => {
  currentDoctor.value = row
  auditDialogVisible.value = true
  auditForm.comment = '资质审核通过'
}

const rejectDoctor = (row: any) => {
  currentDoctor.value = row
  auditDialogVisible.value = true
  auditForm.comment = '资质审核未通过'
}

const confirmApprove = () => {
  ElMessage.success(`审核通过：${currentDoctor.value.doctorName}`)
  auditDialogVisible.value = false
  // 这里应该调用API进行审核状态更新
  fetchDoctorList()
}

const confirmReject = () => {
  ElMessage.warning(`审核拒绝：${currentDoctor.value.doctorName}`)
  auditDialogVisible.value = false
  // 这里应该调用API进行审核状态更新
  fetchDoctorList()
}
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-container {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 8px;
}

.table-container {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.audit-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.doctor-info, .doctor-certificates, .audit-form {
  margin-bottom: 20px;
}

.cert-images {
  display: flex;
  gap: 20px;
  margin-top: 10px;
}

.cert-item {
  flex: 1;
  text-align: center;
}

.cert-item p {
  margin-bottom: 10px;
  font-weight: bold;
}

.cert-item .el-image {
  width: 100%;
  height: 200px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.table-header {
  margin-bottom: 15px;
  display: flex;
  justify-content: flex-start;
}
</style> 